#!/bin/sh
# PCP QA Test No. 1137
# Check new cpu-util.conf derived metrics 
#
# Copyright (c) 2017-2018 Red Hat.  All Rights Reserved.
#

seq=`basename $0`
echo "QA output created by $seq"

. ./common.python

[ $PCP_PLATFORM = linux ] || _notrun "Derived metrics test for Linux CPU metics"
$python -c "from collections import OrderedDict" >/dev/null 2>&1
[ $? -eq 0 ] || _notrun "python collections OrderedDict module not installed"
which pmrep >/dev/null 2>&1 || _notrun "pmrep not installed"

# Note: set PCP_DERIVED_CONFIG explicitly for this test to
# ensure the availability of derived metrics being tested.
config=$PCP_VAR_DIR/config/derived/cpu-util.conf
[ ! -f $config ] && _notrun missing $config

_cleanup()
{
    cd $here
    $sudo rm -rf $tmp $tmp.*
}

status=0
$sudo rm -rf $tmp $tmp.* $seq.full
trap "_cleanup; exit \$status" 0 1 2 3 15

# real QA test starts here
N=`pmprobe -v hinv.ncpu | awk '{print $NF}'`
for m in user nice sys idle intr steal wait
do
    echo checking kernel.all.cpu.$m against derived utilization kernel.cpu.util.$m | tee -a $here/$seq.full
    # kernel.all.cpu.util.X is ms/s and kernel.cpu.util.X is the average %util over all CPUs for mode X.
    # So kernel.all.cpu.util.X should be about the same as kernel.cpu.util.X * (1000 / 100) * Ncpus.
    # Subtract them and check they're equal within a reasonable tolerance
    # (+/- 5%)
    #
    PCP_DERIVED_CONFIG=$config pmrep -t 1 -s 2 kernel.all.cpu.$m kernel.cpu.util.$m 2>$tmp.err >$tmp.out &
    # do some work
    #
    src/chain 3 50000
    wait
    cat $tmp.err
    cat $tmp.out \
    | tee -a $here/$seq.full \
    | $PCP_AWK_PROG '
BEGIN			{ tol_pct = 5 }
# sometimes the colums are in the reversed order (?), so check
# if the kernel.cpu.util.* one comes first ... if so we need to swap
# columns
NR == 1			{ swap = 0
			  if ($1 ~ /^k\.c\.u\./) swap = 1
			  next
			}
swap == 1		{ tmp = $1; $1 = $2; $2 = tmp }
$1 !~ /^[0-9][0-9.]*$/	{ next }
$2 !~ /^[0-9][0-9.]*$/	{ next }
			{ x = $1 - ($2 * 10 * '$N')
			  if ($1 != 0)
			      x = 100.0 * x / $1
			  if (x > tol_pct || x < -tol_pct)
			      print "FAIL " $1 " ? (" $2 "10 * '$N') = " x "%"
			  else
			      print "PASS"
			}'
done

exit
